//
//  ZakatCalculatorViewController.m
//  PrayerTimes
//
//  Created by Igor Karpenko on 6/8/13.
//  Copyright (c) 2013 Igor Karpenko. All rights reserved.
//

#import "ZakatCalculatorViewController.h"
#import "JBTabBarController.h"
#import "ActionSheetPicker.h"

@interface ZakatCalculatorViewController ()

@end

@implementation ZakatCalculatorViewController

#pragma mark - Instance initialization

-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (!self) {
		return nil;
	
	}
	
	self.title = NSLocalizedString(@"Zakat\nCalculator", nil);
	self.tabBarItem.image = [UIImage imageNamed:@"gnr_zakatIcon"];
	self.tabBarItem.selectedImage = [UIImage imageNamed:@"gnr_zakatIcon_active"];
	
	_currencyItems = [[NSArray alloc] initWithObjects:@"EURO", @"GBP", @"USD", nil];
	dataProvider = [DataProvider sharedInstance];
	prayerTimesManager = [PrayerTimesManager sharedInstance];
	
	return self;
}


#pragma mark - Memory managment

-(void) dealloc {
	[_currencyItems release];
	
    [_titleLabel release];
    [_cashLabel release];
    [_savingLabel release];
    [_businessLabel release];
    [_investmenstsLabel release];
    [_goldLabel release];
    [_moneyLabel release];
    [_otherLabel release];
    [_deductLabel release];
    [_totalLabel release];
    [_zakatLabel release];
    [_cashTextField release];
    [_savingTextField release];
    [_businessTextField release];
    [_investmentsTextField release];
    [_goldTextField release];
    [_moneyTextField release];
    [_otherTextField release];
    [_deductTextField release];
    [_totalTextField release];
    [_zakatTextField release];
    [_calculateButton release];
    [_clearButton release];
	[_scrollView release];
	[_overlayImage release];
	
	[_currencyLabel release];
	[_currencyTextField release];
    [super dealloc];
}


#pragma mark - Interface methods

-(void) viewDidLoad {
    [super viewDidLoad];
	
	_overlayImage.image = [_overlayImage.image resizableImageWithCapInsets:UIEdgeInsetsMake(230.0f, 0.0f, 20.0f, 0.0f)];
	_scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, _clearButton.frame.origin.y + _clearButton.frame.size.height + 10.0f);
	
	UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zkt_arrowImage"]];
	arrow.frame = CGRectMake(_currencyTextField.frame.size.width - 20.0f, 5.0f, 11.0f, 13.0f);
	[_currencyTextField addSubview:arrow];
	[arrow release];
}


-(void) viewDidUnload {
    [self setTitleLabel:nil];
    [self setCashLabel:nil];
    [self setSavingLabel:nil];
    [self setBusinessLabel:nil];
    [self setInvestmenstsLabel:nil];
    [self setGoldLabel:nil];
    [self setMoneyLabel:nil];
    [self setOtherLabel:nil];
    [self setDeductLabel:nil];
    [self setTotalLabel:nil];
    [self setZakatLabel:nil];
    [self setCashTextField:nil];
    [self setSavingTextField:nil];
    [self setBusinessTextField:nil];
    [self setInvestmentsTextField:nil];
    [self setGoldTextField:nil];
    [self setMoneyTextField:nil];
    [self setOtherTextField:nil];
    [self setDeductTextField:nil];
    [self setTotalTextField:nil];
    [self setZakatTextField:nil];
    [self setCalculateButton:nil];
    [self setClearButton:nil];
	
	[self setScrollView:nil];
	[self setOverlayImage:nil];
	[self setCurrencyLabel:nil];
	[self setCurrencyTextField:nil];
    [super viewDidUnload];
}


-(void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	int updateDay = [dataProvider.goldUpdateDay integerValue];
	NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
                                                                   fromDate:[NSDate date]];
	int currentday = components.day;
	if (currentday != updateDay) {
		[prayerTimesManager loadGoldPrice];
	}

 	[self changeLanguage];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name: UIKeyboardWillHideNotification object:nil];
}


-(void) viewWillDisappear:(BOOL)animated {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - Action methods

-(IBAction) calculateButtonTapped:(id)sender {
	[self calculateZakat];
}


-(IBAction) clearButtonTapped:(id)sender {
	_cashTextField.text = nil;
    _savingTextField.text = nil;
    _businessTextField.text = nil;
    _investmentsTextField.text = nil;
    _goldTextField.text = nil;
    _moneyTextField.text = nil;
    _otherTextField.text = nil;
    _deductTextField.text = nil;
	
	_totalTextField.text = nil;
	_zakatTextField.text = nil;
}


-(void) currencyWasSelected:(NSNumber *)selectedIndex element:(id)element {
	_currencyTextField.text = [_currencyItems objectAtIndex:[selectedIndex integerValue]];
}


#pragma mark pragma mark - Private methods

-(void) calculateZakat {
	float cash = [_cashTextField.text floatValue];
	float savings = [_savingTextField.text floatValue];
	float business = [_businessTextField.text floatValue];
	float investments = [_investmentsTextField.text floatValue];
	float gold = [_goldTextField.text floatValue];
	float money = [_moneyTextField.text floatValue];
	float other = [_otherTextField.text floatValue];
	float deduct = [_deductTextField.text floatValue];
	
	float totalSum = cash + savings + savings + business + investments + gold + money + other - deduct;
	float zakat = totalSum * 0.025;
	
	float minimumZakat = [self getMinimumZakat];
	NSNumberFormatter * formatter = [[[NSNumberFormatter alloc] init] autorelease];
	formatter.numberStyle = NSNumberFormatterCurrencyStyle;
	formatter.currencyCode = _currencyTextField.text;
	
	if (zakat < minimumZakat) {
		_totalTextField.text = nil;
		_zakatTextField.text = nil;
		NSString *message = [NSString stringWithFormat:@"Your zakat is less than the current NISAB value. NISAB:%@", [formatter stringFromNumber:[NSNumber numberWithFloat:minimumZakat]]];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:message
														message:nil
													   delegate:nil
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	} else {
		_totalTextField.text = [formatter stringFromNumber:[NSNumber numberWithFloat:totalSum]];
		_zakatTextField.text = [formatter stringFromNumber:[NSNumber numberWithFloat:zakat]];
	}
}


-(float) getMinimumZakat {
	NSNumber *goldPrice = nil;
	if ([_currencyTextField.text isEqualToString:@"EURO"]) {
		goldPrice = dataProvider.goldPriceEURO;
	} else if ([_currencyTextField.text isEqualToString:@"USD"]) {
		goldPrice = dataProvider.goldPriceUSD;
	} else {// GBP
		goldPrice = dataProvider.goldPriceGBP;
	}
	
	return [goldPrice floatValue] * 87.48;
}


-(void) changeLanguage {
	_titleLabel.text = AMLocalizedString(@"assetsAndLiabilities", nil);
	_currencyLabel.text = AMLocalizedString(@"currency", nil);
	_cashLabel.text = AMLocalizedString(@"cashAtHome", nil);
	_savingLabel.text = AMLocalizedString(@"savings", nil);
	_businessLabel.text = AMLocalizedString(@"businessStock", nil);
	_investmenstsLabel.text = AMLocalizedString(@"investments", nil);
	_goldLabel.text = AMLocalizedString(@"gold", nil);
	_moneyLabel.text = AMLocalizedString(@"moneyLentOut", nil);
	_otherLabel.text = AMLocalizedString(@"otherIncome", nil);
	_deductLabel.text = AMLocalizedString(@"deductDebts", nil);
	[_calculateButton setTitle:AMLocalizedString(@"calculate", nil) forState:UIControlStateNormal];
	_totalLabel.text = AMLocalizedString(@"totalZakatableAmount", nil);
	_zakatLabel.text = AMLocalizedString(@"yourZakat", nil);
	[_clearButton setTitle:AMLocalizedString(@"clear", nil) forState:UIControlStateNormal];
}


#pragma mark - Notification observers

-(void) keyboardWillShow:(NSNotification *)_notification {
    NSDictionary  *userInfo = [_notification userInfo];
	
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
	
    CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame fromView:nil];
    CGFloat textViewWidth = self.view.frame.size.width;
	
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    _scrollView.frame = CGRectMake(0, 0, textViewWidth, keyboardFrame.origin.y);
    [UIView commitAnimations];
}


-(void) keyboardWillHide:(NSNotification *)_notification {
	NSDictionary  *userInfo = [_notification userInfo];
	
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect keyboardEndFrame;
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
	
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    _scrollView.frame = self.view.frame;
    [UIView commitAnimations];
}


#pragma mark - TextField Delegated methods

// TEXT FIELDS HAS TAGS FROM 10 TO 17
// CURRENCY TEXTFIELD HAVE TAG VALUE 20

-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    int previouTag = textField.tag;
    if (previouTag != 17) {
        UITextField *tempField=(UITextField *)[self.view viewWithTag:previouTag + 1];
        [tempField becomeFirstResponder];
	} else {
		[textField resignFirstResponder];
	}
	return YES;
}


-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
	if (textField.tag == _currencyTextField.tag) {
		[ActionSheetStringPicker showPickerWithTitle:@"Select Currency"
												rows:_currencyItems
									initialSelection:0
											  target:self
									   successAction:@selector(currencyWasSelected:element:)
										cancelAction:nil
											  origin:textField];
		return NO;
	}
	
    return YES;
}


-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (!string.length) {
        return YES;
    }
	
	if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) {
		return NO;
	}
	return YES;
}

@end
